package com.dzl.render;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
 * 
 * @Description:导出word
 * @author liufan
 * @time:2021年4月24日 下午3:58:07
 */
public class FremarkerRender {
	
	protected final Logger logger = Logger.getLogger(getClass());

    private final static String CONTENT_TYPE = "application/msword;charset=utf-8";
    
    private Object data;
    private String fileName;
    private String templateFileName;
    protected HttpServletRequest request;
	protected HttpServletResponse response;
    
    public FremarkerRender(HttpServletRequest request, HttpServletResponse response, Object data, String fileName, String templateFileName) {
        this.fileName = fileName;
        this.data = data;
        this.templateFileName = templateFileName;
        this.request = request;
        this.response = response;
        this.render();
    }
    
    public void render() {
        response.reset();
        try {
			response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
        response.setContentType(CONTENT_TYPE);
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            DocumentHandler dh = new DocumentHandler();
            dh.createDoc(os,data,templateFileName);
        } catch (Exception e) {
        	logger.error(e.getMessage(), e);
        } finally {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
	
}
